from flask import Blueprint, request, jsonify
from src.models.models import db, WeeklyTest, Word
import json
import random

test_bp = Blueprint('test', __name__)

@test_bp.route('/weekly-test/start', methods=['POST'])
def start_weekly_test():
    """开始周测"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        week_index = data.get('week_index', 1)
        
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 生成10道测试题
        words = Word.query.limit(20).all()  # 获取更多单词用于生成选项
        questions = []
        
        for i in range(10):
            if i < len(words):
                correct_word = words[i]
                # 生成选择题
                question = {
                    'id': i + 1,
                    'type': 'multiple_choice',
                    'question': f'What does "{correct_word.en}" mean?',
                    'options': [
                        {'id': 'A', 'text': correct_word.zh},
                        {'id': 'B', 'text': words[(i+1) % len(words)].zh},
                        {'id': 'C', 'text': words[(i+2) % len(words)].zh},
                        {'id': 'D', 'text': words[(i+3) % len(words)].zh}
                    ],
                    'correct_answer': 'A',
                    'word_id': correct_word.id
                }
                questions.append(question)
        
        # 创建测试记录
        test = WeeklyTest(
            user_id=user_id,
            week_index=week_index,
            questions=json.dumps(questions)
        )
        db.session.add(test)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': {
                'test_id': test.id,
                'questions': questions
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@test_bp.route('/weekly-test/submit', methods=['POST'])
def submit_weekly_test():
    """提交周测答案"""
    try:
        data = request.get_json()
        test_id = data.get('test_id')
        answers = data.get('answers')  # [{'question_id': 1, 'answer': 'A'}, ...]
        
        if not all([test_id, answers]):
            return jsonify({'success': False, 'error': 'Missing required fields'}), 400
        
        test = WeeklyTest.query.get_or_404(test_id)
        questions = json.loads(test.questions)
        
        # 计算分数
        correct_count = 0
        total_questions = len(questions)
        
        for answer in answers:
            question_id = answer.get('question_id')
            user_answer = answer.get('answer')
            
            # 找到对应题目
            question = next((q for q in questions if q['id'] == question_id), None)
            if question and question['correct_answer'] == user_answer:
                correct_count += 1
        
        score = (correct_count / total_questions) * 100 if total_questions > 0 else 0
        
        # 生成报告
        report = {
            'total_questions': total_questions,
            'correct_count': correct_count,
            'score': score,
            'accuracy': f'{score:.1f}%',
            'feedback': 'Excellent work!' if score >= 80 else 'Good job!' if score >= 60 else 'Keep practicing!'
        }
        
        # 更新测试记录
        test.score = score
        test.report_json = json.dumps(report)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': report
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@test_bp.route('/weekly-test/<int:test_id>', methods=['GET'])
def get_test_result(test_id):
    """获取测试结果"""
    try:
        test = WeeklyTest.query.get_or_404(test_id)
        return jsonify({
            'success': True,
            'data': test.to_dict()
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

